import {
  Box,
  Button,
  Flex,
  Heading,
  Image,
  Input,
  Stack,
  Text,
  useNumberInput,
  useToast,
} from '@chakra-ui/react';
import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { fetchCatalogItem, type CatalogItem } from '../lib/api';
import { useCart } from '../hooks/useCart';

const ProductDetailPage = () => {
  const { productId } = useParams();
  const [product, setProduct] = useState<CatalogItem | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const toast = useToast();
  const { addItem } = useCart();

  const quantityInput = useNumberInput({
    step: 1,
    defaultValue: 1,
    min: 1,
  });

  useEffect(() => {
    let cancelled = false;

    const load = async () => {
      if (!productId) return;
      setLoading(true);
      setError(null);
      try {
        const item = await fetchCatalogItem(productId);
        if (!cancelled) {
          if (item) {
            setProduct(item);
          } else {
            setError('Product not found');
          }
        }
      } catch (err) {
        if (!cancelled) {
          setError(err instanceof Error ? err.message : 'Failed to load product');
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    };

    void load();
    return () => {
      cancelled = true;
    };
  }, [productId]);

  const handleAddToCart = async () => {
    if (!product) return;
    const quantity = Number(quantityInput.value);
    await addItem({
      productId: String(product.id),
      productName: product.name,
      unitPrice: product.price,
      quantity,
    });
    toast({
      title: 'Added to cart',
      description: `${product.name} x${quantity}`,
      status: 'success',
      duration: 2500,
      isClosable: true,
    });
  };

  if (loading) {
    return (
      <Box bg="white" borderRadius="2xl" border="1px solid" borderColor="gray.200" p={6}>
        <Text color="gray.500">Loading product...</Text>
      </Box>
    );
  }

  if (error || !product) {
    return (
      <Box bg="white" borderRadius="2xl" border="1px solid" borderColor="gray.200" p={6}>
        <Heading size="md">Product Detail</Heading>
        <Text color="red.500" mt={2}>
          {error ?? 'Product not found.'}
        </Text>
      </Box>
    );
  }

  return (
    <Flex
      bg="white"
      borderRadius="2xl"
      border="1px solid"
      borderColor="gray.200"
      p={6}
      direction={{ base: 'column', lg: 'row' }}
      gap={6}
    >
      <Image
        src={
          product.pictureUrl ??
          'https://images.unsplash.com/photo-1510557880182-3d4d3cba35a5?auto=format&fit=crop&w=800&q=80'
        }
        alt={product.name}
        borderRadius="xl"
        width={{ base: '100%', lg: '400px' }}
        objectFit="cover"
      />
      <Stack spacing={4} flex="1">
        <Heading>{product.name}</Heading>
        <Text color="brand.600" fontSize="2xl" fontWeight="700">
          ${product.price.toFixed(2)}
        </Text>
        <Text color="gray.600">{product.description ?? 'No description provided.'}</Text>
        <Stack direction={{ base: 'column', sm: 'row' }} spacing={3} align="center">
          <Input {...quantityInput} flexBasis="120px" />
          <Button colorScheme="brand" onClick={() => void handleAddToCart()}>
            Add to Cart
          </Button>
        </Stack>
      </Stack>
    </Flex>
  );
};

export default ProductDetailPage;
